package com.xxx.dorm.dao.impl;

import com.xxx.dorm.dao.DormManagerDao;
import com.xxx.dorm.domain.Building;
import com.xxx.dorm.domain.Manage;
import com.xxx.dorm.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class DormManagerDaoImpl implements DormManagerDao {

    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Manage> findManager() {
        String sql = "select * from t_user where rid != 1";
        return template.query(sql,new BeanPropertyRowMapper<>(Manage.class));
    }

    @Override
    public Integer addManager(Manage manage) {
        String sql = "insert into t_user(name,sex,phone,rid) values(?,?,?,?)";
        template.update(sql,manage.getName(),manage.getSex(),manage.getPhone(),2);

        //获取做后插入数据的id(用于添加中间件)
        return template.queryForObject(" select last_insert_id()",Integer.class);
    }

    @Override
    public void addManagerToBuild(Integer mid, Integer buildId) {
        String sql = "insert into t_manage_Building(mid,bid) values(?,?)";
        template.update(sql,mid,buildId);
    }

    @Override
    public Manage findById(Integer id) {
        String sql = "select * from t_user where id = ? and rid != 1";
        return template.queryForObject(sql,new BeanPropertyRowMapper<>(Manage.class),id);
    }

    @Override
    public void updateManager(Manage manage) {
        String sql = "update t_user set name = ?,  sex = ? , phone = ? where id = ?";
        template.update(sql,manage.getName(),manage.getSex(),manage.getPhone(),manage.getId());
    }

    /**
     * 通过员工id查找管理的宿舍
     * @param id
     * @return
     */
    @Override
    public List<Building> findBuildBymid(Integer id) {
        String sql;
        sql = "SELECT * FROM t_building WHERE t_building.id in( SELECT bid FROM t_manage_building WHERE t_manage_building.mid = ?)";
        return template.query(sql,new BeanPropertyRowMapper<>(Building.class),id);
    }

    @Override
    public void deleteManager(Integer id) {
        String sql = "delete from t_user where id = ?";
        template.update(sql,id);
    }

    /**
     * 通过mid删除中间件
     * @param id
     */
    @Override
    public void deleteMiddleware(Integer id) {
        String sql = "delete from t_manage_building where mid = ?";
        template.update(sql,id);
    }

    @Override
    public List<Manage> find(String conditions, String information) {
        String sql = null;
        if(conditions.equals("sex")){
            sql = "select * from t_user where sex = ? and rid != 1";
        }else if(conditions.equals("name")){
            sql = "select * from t_user where name = ? and rid != 1";
        }else if(conditions.equals("phone")){
            sql = "select * from t_user where phone = ? and rid != 1";
        }
        return template.query(sql,new BeanPropertyRowMapper<>(Manage.class),information+"");
    }
}
